﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using WsdShop.IService;
using WsdShop.Model;
using WsdShop.Model.SearchModels;
using SqlSugar;
using Infrastructure.Dao;

namespace WsdShop.Service
{
    public class ProductCategoryService : IProductCategoryService
    {
        private SqlSugarClient db;
        public List<Product_Category> ProductCategoryManage(ProductCategorySearchModel search, out int total, out string parentName)
        {
            StringBuilder wherestr = new StringBuilder();
            wherestr.AppendFormat(" ParentId={0} ", search.ParentId);
            if (!string.IsNullOrWhiteSpace(search.Keywords))
            {
                wherestr.AppendFormat(" and CategoryName like '%{0}%'  ", search.Keywords);
            }
            if (search.IsDisplayParm > 0)
            {
                wherestr.AppendFormat(" and IsDisplay={0} ", search.IsDisplayParm == 1 ? 1 : 0);
            }
            var result = BaseService.LoadPageEntities<Product_Category>(search.Skip, search.Take, out total, wherestr.ToString(), search.OrderByFields);
            parentName = "一级分类";
            if (search.ParentId > 0)
            {
                var parentCategoty = BaseService.LoadEntity<Product_Category>(m => m.Id == search.ParentId);
                if (parentCategoty != null && parentCategoty.IsDeleted == false)
                {
                    parentName = parentCategoty.CategoryName + "-二级分类";
                }
            }
            return result;
        }

        /// <summary>
        /// 获取分类数据列表
        /// </summary>
        /// <param name="parentId">上级Id</param>
        /// <returns></returns>
        public List<Product_Category> GetProductCategoryList(int parentId)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Product_Category>().Where(t => t.ParentId == parentId).OrderBy(t => t.DisplayOrder).ToList();
                return list;
            }
        }


        public int[] GetProductCategoryId(int[] ids)
        {
            using (db = DbConfig.GetInstance())
            {
                var list = db.Queryable<Product_Category>().Where(t => ids.Contains(t.Id)).ToList();
                return list.Select(t => t.ParentId).ToArray();
            }
        }

        public bool ChangeCategoryState(int Id, int currentUserId)
        {
            var category = BaseService.LoadEntity<Product_Category>(m => m.Id == Id);
            category.IsHot = category.IsHot != true;
            category.EditTime = DateTime.Now;
            category.EditUserId = currentUserId;
            BaseService.UpdateEntity(category);
            return category.IsHot;
        }

        public Result UpdateCategory(Product_Category model, int currentUserId)
        {
            if (model == null)
            {
                return Result.Failure("传入参数有误");
            }

            var isexist = BaseService.LoadEntitiesCount<Product_Category>(m => m.ParentId == model.ParentId && m.CategoryName == model.CategoryName && m.Id != model.Id);
            if (isexist > 0)
            {
                return Result.Failure("该分类已存在，请重新设置");
            }

            if (model.Id == 0)
            {
                model.AddUserId = currentUserId;
                BaseService.AddEntity(model);
            }
            else
            {
                model.EditTime = DateTime.Now;
                model.EditUserId = currentUserId;
                BaseService.UpdateEntity(model);
            }
            return Result.Success();

        }


        public Result DelCategory(int Id, int currentUserId)
        {
            var isd = true;
            var model = BaseService.LoadEntity<Product_Category>(m => m.Id == Id);
            List<Product_Category> childlist = new List<Product_Category>();
            List<Product> prolist = new List<Product>();
            if (model == null)
            {
                return Result.Failure("该产品分类不存在");
            }
            if (model.ParentId == 0)
            {
                childlist = BaseService.LoadEntities<Product_Category>(m => m.ParentId == model.Id);
                childlist.ForEach(m =>
                {
                    prolist = BaseService.LoadEntities<Product>(p => p.CategoryId == m.Id);
                    if (prolist != null && prolist.Count > 0)
                    {
                        isd = false;
                    }
                });
            }
            else
            {
                prolist = BaseService.LoadEntities<Product>(m => m.CategoryId == model.Id);
                if (prolist != null && prolist.Count > 0)
                {
                    isd = false;
                }
            }

            if (!isd)
            {
                return Result.Failure("该分类下已有产品，无法删除");
            }
            
            model.IsDeleted = true;
            model.EditTime = DateTime.Now;
            model.EditUserId = currentUserId;
            if (BaseService.UpdateEntity(model))
            {
                //var childlist = BaseService.LoadEntities<Product_Category>(m => m.ParentId == model.Id);
                if (childlist != null && childlist.Count > 0)
                {
                    childlist.ForEach(m => { m.IsDeleted = true; m.EditTime = DateTime.Now; m.EditUserId = currentUserId; BaseService.UpdateEntity(m); });
                }
                return Result.Success();
            }
            return Result.Failure("操作失败");
        }

        public List<Product_Category> GetCategoryList()
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Queryable<Product_Category>().Where(m => m.Id > 0).OrderBy(" DisplayOrder Desc,Id Desc ").ToList();
            }
        }

        public List<Product_Category> GetCategoryListForWap()
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Queryable<Product_Category>().Where(m => m.Id > 0 && m.IsDisplay).OrderBy(" DisplayOrder Desc,Id Desc ").ToList();
            }
        }

        public List<Product_Category> GetHotCategory()
        {
            using (var Db = DbConfig.GetInstance())
            {
                return Db.Queryable<Product_Category>().Where(m => m.ParentId > 0 && m.IsHot).OrderBy(" DisplayOrder Desc,Id Desc ").ToList();
            }
        }

    }
}
